import axios from 'axios'
import { GET_TOKEN } from './token'
import {
    ElMessage
} from 'element-plus'

/**
 * This code defines an Axios service instance with interceptors for request and response.
 * The service is configured with a base URL and timeout.
 * The request interceptor adds a token to the request headers if available.
 * The response interceptor handles different HTTP status codes and displays corresponding error messages.
 */

const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 5000,
})

service.interceptors.request.use(config => {
    if(GET_TOKEN()) {
        config.headers.token = GET_TOKEN()
    }

    return config;
})

service.interceptors.response.use( response => {
    return Promise.resolve(response.data) ;
}, error => {
    let message = ''
        // http状态码
        const status = error.response.status
        switch (status) {
            case 401:
                message = 'TOKEN过期'
                break
            case 403:
                message = '无权访问'
                break
            case 404:
                message = '请求地址错误'
                break
            case 500:
                message = '服务器出现问题'
                break
            default:
                message = '网络出现问题'
                break
        }
        // 提示错误信息
        ElMessage({
            type: 'error',
            message
        })

        return Promise.reject(error)
})

export default service